﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net; //添加引用
using System.IO;
public partial class HttpWebRequest异步页 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Response.Write(GetWeb("http://blog.csdn.net/zhihua_1983/archive/2007/06/20/1658718.aspx");
        Response.Write(Postweb("http://localhost:2599/Xml/web用戶控件/Handler.ashx"));

    }

    /// <summary>
    /// HttpWebRequest读取网页 
    /// </summary>
    /// <param name="website">url</param>
    /// <returns></returns>
    public string GetWeb(string website)
    {
        try
        {
            string strHtmlContent = "";
            System.Net.HttpWebRequest myrequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(website);
            myrequest.Timeout = 5000;
           // myrequest.Headers.Set("Pragma", "no-cache");
            System.Net.HttpWebResponse myresponse = (System.Net.HttpWebResponse)myrequest.GetResponse();
            System.IO.Stream mystream = myresponse.GetResponseStream();
            System.Text.Encoding myencoding = System.Text.Encoding.GetEncoding("utf-8");
            System.IO.StreamReader mystreamreader = new System.IO.StreamReader(mystream, myencoding);
            strHtmlContent = mystreamreader.ReadToEnd();
            return strHtmlContent;
        }
        catch(Exception ex)
        {
            return "读取错误"+ex.Message;
        }
    }
    /// <summary>
    /// 合用ＰＯＳＴ发送数据
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public String Postweb(string url)
    {
        string getvalue = "";//初始化得到的返加值

        try
        {
            string data = "<root>\r\n<name>Jack</name>\r\n<age>20</age>\r\n</root>&ff=sdlfjsdkjf朋友处lksdjflkjdslk东东";
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentLength = buffer.Length;
            req.ContentType = "application/x-www-form-urlencoded";
            Stream s = req.GetRequestStream();
            s.Write(buffer, 0, buffer.Length);
            s.Close();
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);

            getvalue = sr.ReadToEnd();

            sr.Close();
            resp.Close();
            

          }
          catch (Exception ex)
        {
            return "读取错误" + ex.Message;
        }
        return getvalue;
    }

}
